package com.shycloud.mido.organ.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.common.core.util.R;
import com.shycloud.mido.organ.api.dto.StudentDetailedDTO;
import com.shycloud.mido.organ.api.dto.TeacherDetailedDTO;
import com.shycloud.mido.organ.api.entity.*;
import com.shycloud.mido.organ.api.util.Constant;
import com.shycloud.mido.organ.api.enums.MessageCodeEnum;
import com.shycloud.mido.organ.mapper.*;
import com.shycloud.mido.organ.service.MemberService;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 会员实现类
 *
 * @author yyy
 * @date 2019-09-24 10:06:58
 */
@Service
@AllArgsConstructor
public class MemberServiceImpl extends ServiceImpl<MemberMapper, MemberEntity>
		implements MemberService {
	private static final PasswordEncoder ENCODER = new BCryptPasswordEncoder();
	private MemberSignMapper memberSignMapper;
	private MemberLevelMapper memberLevelMapper;
	private StudentDetailedMapper studentDetailedMapper;
	private StudentDetailedUnrecordedMapper studentDetailedUnrecordedMapper;
	private TeacherStudentMapper teacherStudentMapper;
	private OrganizationMapper organizationMapper;
	private TeacherDetailedUnrecordedMapper teacherDetailedUnrecordedMapper;
	private TeacherDetailedMapper teacherDetailedMapper;
	private SysUserRoleMapper sysUserRoleMapper;
	private TeacherCourseMapper teacherCourseMapper;
	private TeacherRoyaltyMapper teacherRoyaltyMapper;
	private MemberRoleMapper memberRoleMapper;
	private MemberMapper memberMapper;



	/**
	 * mobiel——注册会员
	 * @param phone 手机号
	 * @param pwd 	密码
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R register(String phone,String pwd){
		//校验手机号用户名是否存在
		QueryWrapper<MemberEntity> query = new QueryWrapper<>();
		query.eq("phone", phone).eq("del_flag", Constant.DEL_FLAG);
		MemberEntity entity =baseMapper.selectOne(query);
		if(entity!=null){
			return new R<>(Boolean.FALSE, MessageCodeEnum.MEMBER_ERROR_103.getMessage());
		}else{
			//注册会员
			regiseter(phone,pwd,null);
			return new R<>(Boolean.TRUE, MessageCodeEnum.SUCCESS.getMessage());
		}
	}

	/**
	 * 会员注册
	 * @param phone
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String saveMember(String phone){
		//校验手机号用户名是否存在
		QueryWrapper<MemberEntity> query = new QueryWrapper<>();
		query.eq("phone", phone).eq("del_flag", Constant.DEL_FLAG);
		MemberEntity entity =baseMapper.selectOne(query);
		if(entity!=null){
			return entity.getId();
		}else{
			String id = IdUtil.simpleUUID();
			//注册会员
			regiseter(phone,"123456",id);
			return id;
		}
	}


	/**
	 * 预注册账号注册
	 * @param phone 手机号
	 * @param pwd  密码
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R readyRegister(String phone,String pwd,String orgId){
		Organization org =organizationMapper.selectById(orgId);
		//校验手机号用户名是否存在
		QueryWrapper<MemberEntity> query = new QueryWrapper<>();
		query.eq("phone", phone).eq("del_flag", Constant.DEL_FLAG);
		MemberEntity entity =baseMapper.selectOne(query);
		if(entity!=null){
			return new R<>(Boolean.FALSE, MessageCodeEnum.MEMBER_ERROR_103.getMessage());
		}else{
			String memberId = regiseter(phone,pwd,null);
			//注册学生
			QueryWrapper<StudentDetailedUnrecordedEntity> studentQuery = new QueryWrapper<>();
			studentQuery.eq("phone", phone).eq("del_flag", Constant.DEL_FLAG);
			StudentDetailedUnrecordedEntity studentEntity = studentDetailedUnrecordedMapper.selectOne(studentQuery);
			StudentDetailedDTO studentDetailedDTO = new StudentDetailedDTO();
			studentDetailedDTO.setMemberId(memberId);
			BeanUtils.copyProperties(studentEntity,studentDetailedDTO);
			studentDetailedMapper.insert(studentDetailedDTO);
			//更新
			studentEntity.setDelFlag(1);
			studentDetailedUnrecordedMapper.updateById(studentEntity);
			return new R<>(Boolean.TRUE, MessageCodeEnum.SUCCESS.getMessage());
		}
	}

	/**
	 * 预注册账号注册
	 * @param phone 手机号
	 * @param pwd  密码
	 * @return
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public R readyTeacherRegister(String phone,String pwd,String orgId){
		//Organization org =organizationMapper.selectById(orgId);
		//校验手机号用户名是否存在
		QueryWrapper<MemberEntity> query = new QueryWrapper<>();
		query.eq("phone", phone).eq("del_flag", Constant.DEL_FLAG);
		MemberEntity entity =baseMapper.selectOne(query);
		if(entity!=null){
			return new R<>(Boolean.FALSE, MessageCodeEnum.MEMBER_ERROR_103.getMessage());
		}else{
			//查询预注册
			String memberId = regiseter(phone,pwd,null);
			QueryWrapper<TeacherDetailedUnrecordedEntity> teacehrQuery = new QueryWrapper<>();
			teacehrQuery.eq("phone", phone).eq("del_flag", Constant.DEL_FLAG);
			TeacherDetailedUnrecordedEntity teacherEntity = teacherDetailedUnrecordedMapper.selectOne(teacehrQuery);

			//设置教师角色
			SysUserRole sysUserRole = new SysUserRole();
			sysUserRole.setUserId(memberId);
			sysUserRole.setOrgId(Integer.parseInt(orgId));
			if (Constant.EDUCATIONAL_ORDINARY.equals(String.valueOf(teacherEntity.getEducational()))) {
				// 为普通老师的时候插入
				sysUserRole.setRoleId(3);

			} else if (Constant.EDUCATIONAL_INSTRUCT.equals(String.valueOf(teacherEntity.getEducational()))) {
				// 为教务老师的时候插入
				sysUserRole.setRoleId(2);
			}
			sysUserRoleMapper.insert(sysUserRole);

			//注册教师
			TeacherDetailedDTO teacherDetailedDTO = new TeacherDetailedDTO();
			BeanUtils.copyProperties(teacherEntity,teacherDetailedDTO);
			teacherDetailedDTO.setId(UUID.randomUUID().toString().replace("-", ""));
			teacherDetailedDTO.setCreateTime(new Date());
			teacherDetailedDTO.setUpdateTime(new Date());
			teacherDetailedDTO.setUpdateUser(memberId);
			teacherDetailedDTO.setCreateUser(memberId);
			teacherDetailedDTO.setMemberId(memberId);
			teacherDetailedMapper.insert(teacherDetailedDTO);

			//新增教师科目
			TeacherCourseEntity teacherCourseEntity = new TeacherCourseEntity();
			teacherCourseEntity.setTeacherId(teacherDetailedDTO.getId());
			// 科目默认钢琴
			teacherCourseEntity.setCourseId("1");
			teacherCourseMapper.insert(teacherCourseEntity);

			//添加教师提成
			TeacherRoyaltyEntity teacherRoyaltyEntity = new TeacherRoyaltyEntity();
			teacherRoyaltyEntity.setTeacherId(teacherDetailedDTO.getId());
			teacherRoyaltyEntity.setType("1");
			teacherRoyaltyEntity.setPrice(new BigDecimal(0));
			teacherRoyaltyEntity.setOrgId(Integer.parseInt(orgId));
			teacherRoyaltyMapper.insert(teacherRoyaltyEntity);
			//更新
			teacherEntity.setDelFlag(1);
			teacherDetailedUnrecordedMapper.updateById(teacherEntity);
			return new R<>(Boolean.TRUE, MessageCodeEnum.SUCCESS.getMessage());
		}
	}

	/**
	 * @author: yyy
	 * @Date: 2019/10/18 11:05
	 * @Description: 如果这个学生还没和这个老师关联，则向org_teacher_student表添加数据，使这个学生和当前老师关联
	 */
	private String regiseter(String phone, String pwd,String id) {
			//注册会员
			MemberEntity entity = new MemberEntity();
			if(StringUtils.isEmpty(id)) {
				entity.setId(IdUtil.simpleUUID());
			}else{
				entity.setId(id);
			}
			entity.setUsername(phone);
			entity.setShowname(phone);
			entity.setPassword(ENCODER.encode(pwd));
			entity.setPhone(phone);
			entity.setCreateTime(LocalDateTime.now());
			entity.setDelFlag(Constant.DEL_FLAG);
			baseMapper.insert(entity);
			// 插入签到信息表
			MemberSignEntity sign = new MemberSignEntity();
			sign.setMemberId(entity.getId());
			memberSignMapper.insert(sign);
			// 插入会员等级表
			MemberLevelEntity level = new MemberLevelEntity();
			level.setLevelId("1");
			level.setMemberId(entity.getId());
			level.setPoints(0L);
			memberLevelMapper.insert(level);

			//赠送一个月高级VIP
			MemberRole memberRole = new MemberRole();
			memberRole.setMemberId(entity.getId());
			memberRole.setRoleCode(Constant.SENIOR_MEMBER_TYEP);
			memberRole.setDelFlag(Constant.DEL_FLAG);
			memberRole.setCreateTime(LocalDateTime.now());
			memberRole.setStartTime(LocalDateTime.now());
			memberRole.setEndTime(LocalDateTime.now().plusMonths(1));
			memberRoleMapper.insert(memberRole);
			return entity.getId();
	}

	/**
	 * 根据机构表的电话号查询member表的数据
	 *
	 * @param phone
	 * @return
	 */
	@Override
	public List<MemberEntity> getMemberByPhone(String username) {
		QueryWrapper<MemberEntity> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("username", username);
		List<MemberEntity> MemberList = memberMapper.selectList(queryWrapper);
		return MemberList;
	}

}